

import UIKit

var screenWidth  = UIScreen.main.bounds.size.width
var screenHeight = UIScreen.main.bounds.size.height

let W_item = 100
let H_item = 200
let margin = 10

let Tag_img = 100

let alerttitle_LS  = NSLocalizedString("Select operation", comment: "")
let openCamera_LS  = NSLocalizedString("Taking pictures", comment: "")
let openGallary_LS = NSLocalizedString("Select from album", comment: "")
let largerView_LS  = NSLocalizedString("To view a larger version", comment: "")
let notalbum_LS    = NSLocalizedString("You do not have permission to access the album", comment: "")
let notCamera_LS   = NSLocalizedString("You did not run the access camera", comment: "")
let title_LS       = NSLocalizedString("Photo wall", comment: "")

class ViewController: UIViewController {

    private lazy var chang_Btn : UIButton = {
        let chang_Btn = UIButton.init()
        chang_Btn.setTitle(NSLocalizedString("change", comment: ""), for: .normal)
        chang_Btn.frame = CGRect.init(x: screenWidth - 100, y: screenHeight - 60, width: 100, height: 30)
        chang_Btn.addTarget(self, action: #selector(changeClick), for: .touchUpInside)
        return chang_Btn
    }()
    
    private lazy var stack_stackView : UIStackView = {
        let stack_stackView = UIStackView.init()
        stack_stackView.frame = CGRect.init(x: 0, y: 100, width: screenWidth, height: screenHeight - 200)
        stack_stackView.axis         = .vertical    // Set the orientation of the layout
        stack_stackView.distribution = .fillEqually // arrangement
        stack_stackView.alignment    = .fill        // Alignment model
        return stack_stackView
    }()
    
    
    
    private lazy var cureImage : UIImageView = {
        let pinchGesture = UIPinchGestureRecognizer(target: self,action: #selector(pinchGestureClick(sender:)))
        let tapGesture = UITapGestureRecognizer(target: self,action: #selector(tapGestureClick(sender:)))
        
        let cureImage = UIImageView.init()
        cureImage.frame = view.bounds
        cureImage.contentMode = .scaleAspectFill
        cureImage.isUserInteractionEnabled = true
        cureImage.isHidden = true
        cureImage.addGestureRecognizer(pinchGesture)
        cureImage.addGestureRecognizer(tapGesture)
        return cureImage
    }()

    var imagePicker = UIImagePickerController()
    
    var Tag_current = 0
    
    var lastScaleFactor : CGFloat! = 1
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
    }
    
    //MARK : 
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        do {
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1)
            {
                if screenWidth != size.width
                {
                    screenWidth  = size.width
                    screenHeight = size.height
                    UIView.animate(withDuration: 0.5)
                    {
                        self.stack_stackView.zc_center = self.view.zc_center
                        self.cureImage.frame = self.view.bounds
                        self.cureImage.zc_center = self.view.zc_center
                        self.chang_Btn.frame = CGRect.init(x: screenWidth - 100, y: screenHeight - 60, width: 100, height: 30)

                    }
                }
            }
        }
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.cureImage.isHidden = true
    }
}

extension ViewController {
    
    // MARK: @objc tapGesClick
    @objc func tapGesClick(tapGes:UITapGestureRecognizer){
        
        Tag_current = tapGes.view?.tag ?? 100
           
        if self.cureImage.isHidden == false
        {
            self.cureImage.isHidden = true
            return
        }
          
        let alert = UIAlertController.init(title: alerttitle_LS, message: nil, preferredStyle: UIAlertController.Style.actionSheet)
       
        alert.addAction(UIAlertAction.init(title: openCamera_LS, style: .default, handler: { (alertaction) in
            self.openCamera()
        }))
        
        alert.addAction(UIAlertAction.init(title: openGallary_LS, style: .default, handler: { (alertaction) in
            self.openGallary()
        }))
        
        alert.addAction(UIAlertAction.init(title: largerView_LS, style: .default, handler: { (alertaction) in
            let img : UIImageView = tapGes.view as! UIImageView
            self.cureImage.image = img.image
            self.cureImage.isHidden = false
        }))
        
        alert.addAction(UIAlertAction.init(title: NSLocalizedString("cancel", comment: ""), style: .cancel, handler: { (alertaction) in }))
        
        self.present(alert, animated: true, completion: nil)

    }
    
    //MARK: - Open the camera
    func openCamera(){
        
        if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerController.SourceType.camera))
        {
            imagePicker.sourceType = UIImagePickerController.SourceType.camera
            imagePicker.allowsEditing = true
            imagePicker.delegate = self
            self.present(imagePicker, animated: true, completion: nil)
        }
        else
        {
            self.AlertClick(title: NSLocalizedString("Warning", comment: ""), message: notCamera_LS)
        }
    }
    
    //MARK: - Choose image from camera roll
    func openGallary(){
        if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary))
        {
            imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary
            imagePicker.allowsEditing = true
            imagePicker.delegate = self
            self.present(imagePicker, animated: true, completion: nil)
        }
        else
        {
            self.AlertClick(title: NSLocalizedString("Warning", comment: ""), message: notalbum_LS)
        }
    }
    
    func AlertClick(title : String , message : String ) -> Void {
        let alert  = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }
    
    // MARK: pinchGestureClick
    @objc func pinchGestureClick(sender: UIPinchGestureRecognizer)
    {
        let factor = sender.scale

        if factor > 1
        {
            cureImage.transform = CGAffineTransform(scaleX: lastScaleFactor+factor-1,y: lastScaleFactor+factor-1)
        }
        else
        {
            cureImage.transform = CGAffineTransform(scaleX: lastScaleFactor*factor,y: lastScaleFactor*factor)
        }

        if sender.state == UIGestureRecognizer.State.ended
        {
            if factor > 1
            {
                lastScaleFactor = lastScaleFactor + factor - 1
            }
            else
            {
                lastScaleFactor = lastScaleFactor * factor
            }
        }
    }
    
    // MARK: tapGestureClick
    @objc func tapGestureClick(sender: UITapGestureRecognizer) -> Void {
        self.cureImage.isHidden = true
    }
    
    // MARK: changeClick
    @objc func changeClick() -> Void
    {
        if self.stack_stackView.axis == .horizontal
        {
            self.stack_stackView.axis = .vertical
        }
        else
        {
            self.stack_stackView.axis = .horizontal
        }
    }
    
}

extension ViewController:  UIImagePickerControllerDelegate, UINavigationControllerDelegate{
  
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        let imgv : UIImageView = self.view.viewWithTag(self.Tag_current) as! UIImageView
        
        if let editedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
        {
            imgv.image = editedImage
        }
        
        picker.isNavigationBarHidden = false
        self.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.isNavigationBarHidden = false
        self.dismiss(animated: true, completion: nil)
    }
}
 
extension ViewController {
    
    func initUI() -> Void {
        
        let itemNum = Int((screenWidth - 20))/(W_item + margin)
        
        for i in 0..<itemNum
        {
            let tapGes = UITapGestureRecognizer(target: self,action: #selector(tapGesClick(tapGes: )))
            
            let photo_imgV = UIImageView.init()
            photo_imgV.backgroundColor = ViewController.UIColorRandom()
            photo_imgV.contentMode = .scaleAspectFill
            photo_imgV.clipsToBounds = true
            photo_imgV.isUserInteractionEnabled = true
            photo_imgV.addGestureRecognizer(tapGes)
            photo_imgV.tag = Tag_img + i
            self.stack_stackView.addArrangedSubview(photo_imgV)
        }
        view.addSubview(self.stack_stackView)
        view.addSubview(self.cureImage)
        view.addSubview(self.chang_Btn)
    }
    
}

extension ViewController {

    class func UIColorRandom() -> UIColor
    {
        let color: UIColor = UIColor.init(red: (((CGFloat)((arc4random() % 256)) / 255.0)), green: (((CGFloat)((arc4random() % 256)) / 255.0)), blue: (((CGFloat)((arc4random() % 256)) / 255.0)), alpha: 1.0);
        return color;
    }
}

